package com.finals.media.service;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.media.MediaPlayer;

public class MusicePlayer {

	Context context;

	MediaPlayer mediaPlayer;

	Timer mTimer;

	DownloadThread mDownloadThread = null;

	public MusicePlayer(Context context) {
		this.context = context;
		mediaPlayer = new MediaPlayer();
		mTimer = new Timer();
	}

	public int getDuration() {
		if (mediaPlayer != null) {
			return mediaPlayer.getDuration();
		}
		return 0;
	}

	public int getCurrentPosition() {
		if (mediaPlayer != null) {
			return mediaPlayer.getCurrentPosition();
		}
		return 0;
	}

	public boolean Prepare(File path, int length) {
		boolean result = false;
		mediaPlayer.reset();
		try {
			mediaPlayer.setDataSource(path.getAbsolutePath());
			mediaPlayer.prepare();
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	public void Play() {
		if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
			geTimerTask();
			mTimer.schedule(mTask, 0, 20);
			mediaPlayer.start();
		}
	}

	public void Pause() {
		CancelTask();
		if (mediaPlayer != null && mediaPlayer.isPlaying()) {
			mediaPlayer.pause();
		}
	}

	public void onDestroy() {
		CancelTask();
		if (mediaPlayer != null) {
			if (mediaPlayer.isPlaying()) {
				mediaPlayer.stop();
			}
			mediaPlayer.reset();
			mediaPlayer.release();
		}
		mediaPlayer = null;
	}

	TimerTask mTask;

	public void PlayMusic(String pathString) {
		if (mDownloadThread != null) {
			mDownloadThread.StopDownload();
			mDownloadThread = null;
		}
		mDownloadThread = new DownloadThread(context, this, pathString);
		mDownloadThread.start();
	}

	public void geTimerTask() {
		CancelTask();
		mTask = new TimerTask() {

			@Override
			public void run() {
				if (!CanPlay()) {
					Pause();
				}
			}
		};
	}

	private void CancelTask() {
		if (mTask != null) {
			mTask.cancel();
			mTask = null;
		}
	}

	public boolean CanPlay() {
		boolean result = true;
		try {
			float current = mediaPlayer.getCurrentPosition();
			float total = mediaPlayer.getDuration();
			float currentCache = total * mDownloadThread.getCachePercent();
			if (current > currentCache - 15) {
				result = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
